from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.urls import reverse_lazy, reverse

from .forms import (
    UserLoginForm, StudentRegistrationForm, TeacherRegistrationForm,
    UserProfileUpdateForm, PasswordChangeForm
)


def index_view(request):
    """首页视图，显示MP4背景和进入按钮"""
    return render(request, 'accounts/index.html')


class LoginView(View):
    """用户登录视图"""
    template_name = 'accounts/login.html'
    form_class = UserLoginForm
    
    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})
    
    def post(self, request):
        form = self.form_class(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                messages.success(request, f'欢迎回来，{user.username}！')
                return redirect('home')
        return render(request, self.template_name, {'form': form})


class StudentRegistrationView(View):
    """学生注册视图"""
    template_name = 'accounts/register.html'
    form_class = StudentRegistrationForm
    
    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form': form, 'user_type': 'student'})
    
    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, '注册成功！请登录。')
            return redirect('login')
        return render(request, self.template_name, {'form': form, 'user_type': 'student'})


class TeacherRegistrationView(View):
    """教师注册视图"""
    template_name = 'accounts/register.html'
    form_class = TeacherRegistrationForm
    
    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form': form, 'user_type': 'teacher'})
    
    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, '注册成功！请登录。')
            return redirect('login')
        return render(request, self.template_name, {'form': form, 'user_type': 'teacher'})


def logout_view(request):
    """用户登出视图"""
    logout(request)
    messages.success(request, '您已成功登出！')
    return redirect('index')


@method_decorator(login_required, name='dispatch')
class ProfileView(View):
    """用户个人信息视图"""
    template_name = 'accounts/profile.html'
    
    def get(self, request):
        profile_form = UserProfileUpdateForm(instance=request.user)
        password_form = PasswordChangeForm(user=request.user)
        context = {
            'profile_form': profile_form,
            'password_form': password_form,
        }
        return render(request, self.template_name, context)
    
    def post(self, request):
        if 'update_profile' in request.POST:
            profile_form = UserProfileUpdateForm(request.POST, instance=request.user)
            password_form = PasswordChangeForm(user=request.user)
            
            if profile_form.is_valid():
                profile_form.save()
                messages.success(request, '个人信息更新成功！')
                return redirect('profile')
            
        elif 'change_password' in request.POST:
            profile_form = UserProfileUpdateForm(instance=request.user)
            password_form = PasswordChangeForm(user=request.user, data=request.POST)
            
            if password_form.is_valid():
                new_password = password_form.cleaned_data.get('new_password')
                request.user.set_password(new_password)
                request.user.save()
                update_session_auth_hash(request, request.user)
                messages.success(request, '密码更新成功！')
                return redirect('profile')
        
        context = {
            'profile_form': profile_form,
            'password_form': password_form,
        }
        return render(request, self.template_name, context)
